<template>
  <base-breadcrumb
    class="UpdateOrgLife-container fixed-container"
    :title="breadcrumbTitle"
  >
    <a-spin :spinning="loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="formInfo"
          :form-list="formItemList"
          @selectNode="handleSelectOrg"
        />
        <title-name title="相关附件" />
        <UploadTableNew
          ref="uploadTable"
          :disabled="isDisabled"
          business-code="PARTY01"
          :mode="pageType"
          :request-fn="getFileList"
        />
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          提交
        </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { getFiles, getDetail, addData, editData } from '@/api/partyMasses/partyManage/orgLife.js'
import PartyTreeSelect from '../../componments/partyTreeSelect.vue'
import Vue from 'vue'
import Moment from 'moment'
import { PARTY_TYPE_MAP } from '@/config/businessConfig.js'
import Selector from '@/components/Select/Selector.vue'

export default {
  name:'a'+ Date.now(),
  data() {
    return {
      isHiddenOrgSelect: false,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false,
      },
      formInfo: {},
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增组织生活',
        edit: '编辑组织生活',
        look: '组织生活详情',
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '组织生活名称',
          keyName: 'lifeName',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        {
          label: '举办组织',
          keyName: 'partyOrgId',
          viewName: 'partyOrgName',
          type: PartyTreeSelect,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          hidden: this.isHiddenOrgSelect,
          attrs: {
            returnInitNode: true,
            orgStatus: 1
          },
        },
        {
          label: '组织生活日期',
          keyName: 'lifeTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
        },
        {
          label: '组织生活类型',
          keyName: 'lifeTypeId',
          viewName: 'lifeTypeName',
          type: Selector,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            urlType: 'union',
            selectType: 26,
          },
        },
        {
          label: '组织生活地址',
          keyName: 'address',
          type: 'BaseInput',
          span: 16,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        {
          label: '主持人',
          keyName: 'presenter',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        {
          label: '记录人',
          keyName: 'recorder',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        {
          label: '参会人',
          keyName: 'attendee',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        {
          label: '学习内容概述',
          keyName: 'descriptionContent',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          span: 24,
        },
        {
          label: '会议纪要',
          keyName: 'meetingMinutes',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          span: 24,
        },
        {
          label: '组织生活级别',
          keyName: 'lifeLevelName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true,
        },
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    },
  },
  created() {
    this.initPage()
    this.getDetailReq()
  },
  methods: {
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.formInfo = {
        ...this.formInfo,
        creatorName: userInfo.name,
        lifeTime: curDate,
        createTime: curDate,
      }
    },
    handleSelectOrg(key, data) {
      const { orgType, id } = data
      this.formInfo = {
        ...this.formInfo,
        partyOrgId: id,
        lifeLevelName: PARTY_TYPE_MAP[orgType],
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('partyOrgId')
      })
    },
    async getDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id,
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
        }
        this.isHiddenOrgSelect = true
        this.$nextTick(() => {
          this.isHiddenOrgSelect = false
        })
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    getFileList(params) {
      if (!this.$route.query.id) {
        return Promise.resolve()
      }
      return getFiles({ ...params, query: { lifeId: this.$route.query.id, type: 2 } })
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const { addIds, delIds, loadList } = this.$refs.uploadTable.getChangedFileIds()
        // 没有新增，并且请求到的文件列表也为空，那么可判断当前文件表格为空
        if(addIds.length === 0 &&  !loadList.length){
          this.$message.error('请上传附件！');
          this.loadingState[actionName] = false
          return
        }
        const params = {
          ...this.formInfo,
          addFileIds: addIds,
          removeFileIds: delIds,
        }
        const fn = this.pageType === 'add' ? addData : editData
        await fn(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        this.$refs.uploadTable.batchDeleteFile() // 删除文件
        this.$multiTab.close()
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    },
  },
}
</script>

<style lang="less" scoped>
.file-tips {
  color: #999999;
  padding-left: 50px;
}
</style>
